<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { usePagination, useSwitchable, useTableSelection } from '@/utils/hooks'
import { handleApi } from '@/utils/alert'
import { TableColumnType, message, Modal } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import QueryForm from './supporter-post-orders-form.vue'
import { deliveryOrder, getSPostOrders, SupplyChainOrderRemark } from "@/api/order.ts";
import { dateFormatter } from "@/utils/common.ts";
import { OrderStatusProps } from "@/components/order-status.vue";
import Copy from "@/components/copy.vue";
import OrderStatus from "@/components/order-status.vue";
import GoodsDetail from "@/components/goods-detail.vue";
import PostDetail from "@/components/post-detail.vue";
import PrinterConnection, { FormState as PrinterForm } from "./printer-connection.vue";
import PrinterTask, { PrinterTaskProps } from "#/supporter-post-orders/printer-task.vue";
import OrderErp from "@/components/order-erp.vue";
import PostDate from "@/components/post-date.vue";
import ExpressCell from "@/components/express-cell.vue";
import { recoverWaybillOrder } from "@/api/waybill.ts";
import ManualShip from "#/supporter-post-orders/manual-ship.vue";
import OrderRemark from '@/components/order-remark.vue'
import OrderRemarkForm, { OrderRemarkEvent } from '@/components/order-remark-form.vue'


const queryRef = ref<typeof QueryForm>()

const { dataSource, pagination, fetch, params, loading } = usePagination(getSPostOrders, handleApi)
const { state: printerModalState, on: printerModalOn, off: printerModalOff } = useSwitchable()
const { state: taskModalState, on: taskModalOn, off: taskModalOff } = useSwitchable()
const { state: shipModalState, on: shipModalOn, off: shipModalOff } = useSwitchable()
const { state: remarkModalState, on: remarkModalOn, off: remarkModalOff } = useSwitchable()
const taskProps = reactive<PrinterTaskProps>({})
const shippingOrder = ref<IOrder | undefined>()
const remarking = ref<IOrder | undefined>()

const status = ref<number>(-2)
const columns: (TableColumnType & DataIndex<IOrder>)[] = [
  { key: 'goods_info', title: '商品信息', width: 300 },
  { key: 'price&num', title: '单价/数量', width: 100 },
  { key: 'post_info', title: '收件人信息', width: 200 },
  { key: 'seller_words', title: '订单备注', width: 250 },
  { key: 'tracking_number', title: '快递单号', width: 200 },
  { key: 'status', title: '状态', width: 200 },
  { key: 'erp', title: 'ERP信息', width: 200 },
  { key: 'create_time', dataIndex: 'order_create_time', title: '创建时间', width: 200 },
  { key: 'post_date', title: '发货时间', width: 150 },
  { key: 'action', title: '操作', width: 100, fixed: 'right' }
]

const onTableChange: TableProps['onChange'] = (pg) => {
  params.value.page = pg.current
  params.value.pagesize = pg.pageSize
  fetch()
}

onMounted(() => {
  params.value = {
    page: params.value.page,
    pagesize: params.value.pagesize,
    order_status: status.value
  }
  fetch()
})

const { selectedKeys, onSelectedChange } = useTableSelection()

const onFormSubmit = (p: PaginateQuery<SupportPostOrderQuery>) => {
  params.value = {
    ...p,
    page: params.value.page,
    pagesize: params.value.pagesize
  }
  fetch()
}
const onFormButton = (key: 'print' | 'confirm_ship') => {
  if (key === 'print') {
    if (selectedKeys.value.length === 0) {
      message.error('请先勾选要打印的快递单')
      return
    }
    printerModalOn()
  } else if (key === 'confirm_ship') {
    if (selectedKeys.value.length === 0) {
      message.error('请先勾选要确认发货的订单')
      return
    }
    const selectedOrders = dataSource.value?.filter(i => i.order_status === 2 && i.tracking_number && selectedKeys.value.includes(i.id)) || []
    if (selectedOrders.length === 0) {
      message.error('已勾选的订单中不包含可以确认发货的订单')
    } else if (selectedOrders.length !== selectedKeys.value.length) {
      message.warn('已勾选的订单中包含不可确认发货的订单, 已为您排除')
    }
    selectedKeys.value = selectedOrders.map(i => i.id)
    if (selectedOrders.length) {
      confirmDeliveryOrders(selectedOrders)
    }
  }
}

const onPrinterAndTemplateSelected = (p: PrinterForm) => {
  console.log(p.printer,'打印机名称')
  printerModalOff()
  taskProps.printer = p
  taskProps.orders = dataSource.value?.filter(i => selectedKeys.value.includes(i.id))
  taskModalOn()
}

const selectedOrders = computed(() => dataSource.value?.filter(i => selectedKeys.value.includes(i.id)))


const confirmDeliveryOrders = async (records: IOrder[]) => {
  loading.value = true
  const res = await deliveryOrder(records.map(i => i.order_id)).catch(handleApi)
  if (res) {
    if (res.data?.error_data?.length) {
      Modal.warning({
        title: `确认发货失败: ${res.data.error_data.length} 条`,
        content: res.data.error_data.map(i => `订单号: ${i.order_id}, 信息: ${i.msg}`).join('\n'),
        width: '500px'
      })
    } else {
      message.success('操作成功')
    }
    await fetch()
  }
  loading.value = false
}

const recOrder = async (record: IOrder) => {
  loading.value = true
  const res = await recoverWaybillOrder({
    track_no: record.tracking_number,
    order_id: record.order_id
  }).catch(handleApi)
  if (res) {
    message.success('操作成功')
    await fetch()
  }
  loading.value = false
}

const shipping = (record: IOrder) => {
  shippingOrder.value = record
  shipModalOn()
}

const checkUpdatable = (record: IOrder) => {
  return (record.order_status === 30 && !record.tracking_number) ||
    (record.auto_create_waybill === 2 && record.tracking_number)
}
const updateTrackNumberSuccess = () => {
  fetch()
  shipModalOff()
}

const closeTaskModal = () => {
  fetch()
  taskModalOff()
}

const startRemark = (order: IOrder) => {
  remarking.value = order
  remarkModalOn()
}

const remarkOrder = async ({ remark }: OrderRemarkEvent) => {
  if (remarking.value) {
    const res = await SupplyChainOrderRemark({ remark, order_id: remarking.value.order_id }).catch(handleApi)
    if (res) {
      message.success(res.message)
      await fetch()
      remarking.value = undefined
      remarkModalOff()
    }
  }
}

const onStatusChange = () => {
  if (queryRef.value) {
    queryRef.value.setFields('order_status', status.value)
    onFormSubmit(queryRef.value.getValues())
  }
}

</script>


<template>
  <div class="px-4 py-8">
    <QueryForm @submit="onFormSubmit" @button="onFormButton" ref="queryRef"></QueryForm>
  </div>

  <div class="h-full w-ful space-y-1">
    <div class="pl-4">
      <ATabs tab-position="top" class="w-full" v-model:active-key="status" @change="onStatusChange">
        <ATabPane tab="全部" :key="-1"></ATabPane>
        <ATabPane tab="待打单" :key="-2"></ATabPane>
<!--        <ATabPane tab="备货中" :key="2"></ATabPane>-->
        <ATabPane tab="已发货" :key="40"></ATabPane>
        <ATabPane tab="已完成" :key="70"></ATabPane>
      </ATabs>
    </div>

    <ATable :scroll="{ x: 2600 }"
            :columns="columns"
            :data-source="dataSource"
            :loading="loading"
            :pagination="pagination"
            row-key="id"
            :row-selection="{ selectedRowKeys: selectedKeys, onChange: onSelectedChange }"
            @change="onTableChange">
      <template #bodyCell="{ column, value, record }">

        <template v-if="column.key === 'goods_info'">
          <div class="flex text-xs text-gray-600 justify-between">
            <Copy :value="record.order_id" class="opacity-80">
              <span class="text-nowrap text-ellipsis">订单编号: {{ record.order_id }}</span>
            </Copy>
          </div>
          <GoodsDetail v-bind="record"></GoodsDetail>
        </template>

        <template v-if="column.key === 'price&num'">
          <div class="h-full">
            <div class="text-gray-600 flex flex-col space-y-1 h-14 first:mt-6 text-sm items-center">
              <span>x{{ record.goods_count }}</span>
            </div>
          </div>
        </template>

        <template v-if="column.key === 'post_info'">
          <PostDetail v-bind="record"></PostDetail>
        </template>

        <template v-if="column.key === 'seller_words'">
          <order-remark v-bind="record"></order-remark>
        </template>

        <template v-if="column.key === 'tracking_number'">
          <ExpressCell v-bind="record"></ExpressCell>
        </template>

        <template v-if="column.key === 'status'">
          <OrderStatus v-bind="record as OrderStatusProps"></OrderStatus>
        </template>

        <template v-if="column.key === 'erp'">
          <OrderErp v-bind="record"></OrderErp>
        </template>

        <template v-if="column.key === 'create_time'">
          {{ dateFormatter(value) }}
        </template>

        <template v-if="column.key === 'post_date'">
          <PostDate v-bind="record"></PostDate>
        </template>

        <template v-if="column.key === 'action'">
          <div class="flex flex-col items-center">
            <AButton type="link" @click="startRemark(record)">订单备注</AButton>

            <APopconfirm
              title="是否确认"
              :disabled="record.order_status !== 30 || !record.tracking_number"
              @confirm="confirmDeliveryOrders([record])"
            >
              <AButton type="link" :disabled="record.order_status !== 30 || !record.tracking_number">确认发货</AButton>
            </APopconfirm>

            <APopconfirm
              title="是否回收单号"
              :disabled="record.order_status !== 30 || !record.tracking_number || record.auto_create_waybill !== 1"
              @confirm="recOrder(record)"
            >
              <AButton type="link" :disabled="record.order_status !== 30 || !record.tracking_number || record.auto_create_waybill !== 1">回收单号</AButton>
            </APopconfirm>

            <AButton type="link" @click="shipping(record)" :disabled="!checkUpdatable(record)">手动填单</AButton>
          </div>
        </template>
      </template>
    </ATable>
  </div>

  <AModal v-model:open="printerModalState" :footer="null" width="500px" :closable="false" destroyOnClose>
    <PrinterConnection @cancel="printerModalOff"
                       @submit="onPrinterAndTemplateSelected"
                       :orders="selectedOrders"></PrinterConnection>
  </AModal>

  <AModal
    v-model:open="taskModalState"
    :footer="null"
    width="1000px"
    :closable="false"
    :mask-closable="false"
    :keyboard="false"
    destroyOnClose
  >
    <PrinterTask v-bind="taskProps" @close="closeTaskModal"></PrinterTask>
  </AModal>

  <AModal v-model:open="shipModalState" :footer="null" width="500px" destroy-on-close>
    <ManualShip :order="shippingOrder" @success="updateTrackNumberSuccess"></ManualShip>
  </AModal>

  <AModal v-model:open="remarkModalState" :footer="null" width="500px" destroy-on-close>
    <OrderRemarkForm @submit="remarkOrder" :order="remarking"></OrderRemarkForm>
  </AModal>
</template>